package com.authsphere.security.social.common.configuration;

import com.authsphere.security.social.common.AuthRequestFactory;
import com.authsphere.security.social.common.ThirdPartyAuthStateCache;
import me.zhyd.oauth.cache.AuthStateCache;
import me.zhyd.oauth.request.AuthRequest;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;

import java.util.Map;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/25 09:20
 **/
@Configuration
public class SocialCommonConfiguration {

    @Bean
    public AuthStateCache thirdPartyAuthStateCache(final StringRedisTemplate stringRedisTemplate) {
        return new ThirdPartyAuthStateCache(stringRedisTemplate);
    }

    @Bean
    ApplicationListener<ContextRefreshedEvent> applicationListener() {
        return event -> {
            ApplicationContext context = event.getApplicationContext();
            Map<String, AuthRequest> authRequestMap = context.getBeansOfType(AuthRequest.class);
            if (CollectionUtils.isEmpty(authRequestMap)) {
                return;
            }
            authRequestMap.forEach(AuthRequestFactory::register);
        };
    }
}
